package mysql

import (
	"gorm.io/gorm"
	"video-guard/videorpc/videorpc"
)

type VideoInfo struct {
	gorm.Model
	UserId        int    `gorm:"type:int(11);not null;comment:用户ID"`
	Title         string `gorm:"type:varchar(20);not null;;comment:视频标题"`
	VideoCategory string `gorm:"type:varchar(20);not null;;comment:视频URL"`
	CoverLink     string `gorm:"type:varchar(500);not null;;comment:视频分类"`
	VideoIntro    string `gorm:"type:varchar(500);not null;;comment:视频简介"`
	VideoStatus   int64  `gorm:"type:int(11);default:0;comment:视频状态"`
	TopicId       int64  `gorm:"type:int(11);default:0;comment:话题id"`
	LikeNum       int64  `gorm:"type:int(11);default:0;comment:点赞数"`
	CommentNum    int64  `gorm:"type:int(11);default:0;comment:评论数"`
	CollectNum    int64  `gorm:"type:int(11);default:0;comment:收藏数"`
	PlayNum       int64  `gorm:"type:int(11);default:0;comment:播放量"`
}

func (i *VideoInfo) VideoDel(db *gorm.DB, id int64) error {
	return db.Where("video_infos.id=?", id).Delete(i).Error
}

func (i *VideoInfo) VideoUpdate(db *gorm.DB) error {
	return db.Updates(i).Error
}

func (i *VideoInfo) FindVidepByVideoId(db *gorm.DB, id int64) error {
	return db.Where("video_infos.id=?", id).First(i).Error
}

func (i *VideoInfo) UpdateVedio(db *gorm.DB, id int64) error {
	return db.Model(&VideoInfo{}).Where("video_infos.id=?", id).Update("play_num", gorm.Expr("play_num+ ?", 1)).Error
}

func (i *VideoInfo) VideoList(db *gorm.DB, in *videorpc.VideoListTRequest) []*videorpc.VideoList {
	var video []*videorpc.VideoList
	tx := db.Debug().Model(&VideoInfo{}).Select("video_infos.*",
		"user_infos.nick_name",
		"user_infos.avatar_link",
		"topic_infos.topic_name",
		"topic_infos.topic_intro").Joins("LEFT JOIN user_infos ON video_infos.user_id = user_infos.id").
		Joins("LEFT JOIN topic_infos on video_infos.topic_id = topic_infos.id").Scopes(Paginate(int(in.Page), int(in.Size)))
	if in.SortType == 0 {
		tx = tx.Order("play_num")
	} else if in.SortType == 1 {
		tx = tx.Order("video_infos.created_at DESC")
	}
	tx.Find(&video)
	return video
}

func (i *VideoInfo) UpdateVedioNum(db *gorm.DB, id int64) error {
	return db.Model(&VideoInfo{}).Where("video_infos.id=?", id).Update("collect_num", gorm.Expr("collect_num- ?", 1)).Error
}

func VideoShow(db *gorm.DB) videorpc.VideoList {
	var video videorpc.VideoList
	db.Debug().Model(&VideoInfo{}).Select("video_infos.*",
		"user_infos.nick_name",
		"user_infos.avatar_link",
		"topic_infos.topic_name",
		"topic_infos.topic_intro").Joins("LEFT JOIN user_infos ON video_infos.user_id = user_infos.id").
		Joins("LEFT JOIN topic_infos on video_infos.topic_id = topic_infos.id").First(&video)
	return video
}
